package com.kit.data.kitopeso.tools;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;

import androidx.exifinterface.media.ExifInterface;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImgUitls {

    public static File compressToTargetSize(Context context, Uri imageUri, int maxSizeKB, String path) {
        try {


            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            InputStream is = context.getContentResolver().openInputStream(imageUri);
            BitmapFactory.decodeStream(is, null, options);
            closeQuietly(is);


            options.inSampleSize = calculateInSampleSize(options);
            options.inJustDecodeBounds = false;



            Bitmap bitmap;
            try {
                is = context.getContentResolver().openInputStream(imageUri);
                bitmap = BitmapFactory.decodeStream(is, null, options);
            } catch (OutOfMemoryError e) {
                options.inSampleSize *= 2; // 采样率翻倍
                closeQuietly(is);
                is = context.getContentResolver().openInputStream(imageUri);
                bitmap = BitmapFactory.decodeStream(is, null, options);
            }


            int rotation = getRotationFromExif(context, path);
            LogUtil.e("me", "-rotation->" + rotation);
            bitmap = rotateBitmap(bitmap, rotation);




            if (bitmap != null) {
                File outputFile = createTempFile(context);
                compressToFile(bitmap, outputFile, maxSizeKB * 1024L);

                bitmap.recycle();
                return outputFile;
            }
        } catch (IOException ignored) {

        }
        return null;
    }


    private static void compressToFile(Bitmap bitmap, File outputFile, long maxBytes) throws IOException {
        int quality = 90;
        FileOutputStream fos = new FileOutputStream(outputFile);

        do {
            fos.flush();
            fos.getChannel().truncate(0);
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
            quality -= 10;
        } while (outputFile.length() > maxBytes && quality >= 10);

        fos.close();
    }


    private static int calculateInSampleSize(BitmapFactory.Options options) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > 1024 || width > 1024) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            while ((halfHeight / inSampleSize) >= 1024
                    && (halfWidth / inSampleSize) >= 1024) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }


    private static int getRotationFromExif(Context context, String imagePath) {

        ExifInterface exif;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try (InputStream inputStream = new FileInputStream(imagePath)) {
                exif = new ExifInterface(inputStream);
            } catch (IOException e) {
                return 0;
            }
        } else {
            try {
                exif = new ExifInterface(imagePath);
            } catch (IOException e) {
                return 0;
            }
        }

        boolean isOppo = Build.MANUFACTURER.equalsIgnoreCase("OPPO")
                || Build.MANUFACTURER.equalsIgnoreCase("realme");
        if (isOppo) {
           return 0;
        }

        String orientation = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        if (orientation == null) {

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(imagePath, options);
            return (options.outWidth > options.outHeight) ? 90 : 0;
        } else {
            return exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL
            );
        }
    }

    private static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
        if (degrees != 0 && bitmap != null) {
            Matrix matrix = new Matrix();
            matrix.postRotate(degrees);
            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }
        return bitmap;
    }

    private static File createTempFile(Context context) throws IOException {
        String fileName = "compressed_" + System.currentTimeMillis() + ".jpg";
        return File.createTempFile(fileName, null, context.getCacheDir());
    }

    private static void closeQuietly(InputStream is) {
        try {
            if (is != null) is.close();
        } catch (IOException ignored) {
        }
    }

}
